class ScheduledRecordsController < ApplicationController
  before_filter :authenticate_user!

  # GET /scheduled_records
  def index
    render :json => current_user.scheduled_records.as_json
  end

  # POST /scheduled_records
  def create
    @scheduled_record = ScheduledRecord.new(getScheduledRecord())

    if @scheduled_record.save
      statusOk(@scheduled_record)
    else
      statusError(@scheduled_record)
    end
  end

  # POST /scheduled_records/1
  def update
    @scheduled_record = ScheduledRecord.find_by_id(params[:id])
    if @scheduled_record.nil?
      statusError nil, :entity_not_found, "entity not found"
    elsif @scheduled_record.update_attributes(getScheduledRecord())
      statusOk(@scheduled_record)
    else
      statusError(@scheduled_record)
    end
  end

  # POST /scheduled_records/destroy/1
  def destroy
    @scheduled_record = ScheduledRecord.find_by_id(params[:id])
    if @scheduled_record.nil?
      statusError nil, :entity_not_found, "entity not found"
    elsif @scheduled_record.destroy
      statusOk(@scheduled_record)
    else
      statusError @scheduled_record
    end
  end

  private
    def getScheduledRecord
      sr = params[:scheduled_record]
      sr["wallet"] = current_user.wallets.find_by_name(sr["wallet"])

      sr
    end

    def statusOk scheduled_record
      render :json => {
          :status => :ok,
          :record => scheduled_record.as_json
      }
    end

    def statusError scheduled_record, status = :unprocessable_entity, message = nil
      render :json => {
          :status => status,
          :errors => message || scheduled_record.errors,
        }
    end
end
